import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { View, StyleSheet, Linking } from 'react-native';
import { ListItem } from 'react-native-elements';
import { filter } from 'graphql-anywhere';
import OrderListItem from './OrderListItem';
import InfiniteList from '../widgets/InfiniteList';
import { loadMoreData, executor, toast } from '../utils';
import Communications from 'react-native-communications';

const styles = StyleSheet.create({
  footer: {
    textAlign: 'center',
    color: 'gray'
  }
});

class OrderList extends Component {
  state = {}
  onRefresh = () => {
    this.props.refetch()
      .then(() => toast('Refresh complete'));
    toast('Refreshing');
  }
  renderHeader = () => <ListItem title='Refresh' titleStyle={styles.footer} onPress={this.onRefresh} hideChevron/>
  renderItem = ({item}) => {
    if (this.props.history) {
      return <ListItem title={`#${item.displayId}`} onPress={()=>this.props.onSelect(item)}
        subtitle={`${item.shipping.title}: ${item.shipping.displayDate}`}/>;
    } else {
      return <OrderListItem onCall={this.onCall} onSelect={this.props.onSelect}
        total={this.props.countMap&&this.props.countMap[item.userId]} onSms={this.props.onSms}
        order={filter(OrderListItem.fragments.order, item)} calling={this.state[item.shipping.contact]}/>;
    }
  }
  componentWillReceiveProps(nextProps) {
    this.props.onUpdateCount(nextProps.pickupCount, nextProps.deliveryCount, nextProps.locationCount);
  }
  onCall = (contact) => {
    executor(this.props.getUserContact, contact)
      .then(({res}) => {
        if (res&&res.getUserContact) {
          Communications.phonecall(res.getUserContact, false);
        }
        this.setState({[contact]: false});
      });
    this.setState({[contact]: true});
  }
  render() {
    let { orders, loading, refetch, fetchMore, filter } = this.props;
    if (orders) {
      if (filter==='pickup') {
        orders = orders.filter(({shipping}) => shipping.title[0]&&(shipping.title[0]==='P'));
      } else if (filter==='delivery') {
        orders = orders.filter(({shipping}) => shipping.title[0]&&(shipping.title[0]!=='P'));
      }
    }

    return <InfiniteList top hideEmpty extraData={this.state} datas={orders} loading={loading}
      refetch={refetch} fetchMore={fetchMore}
      renderItem={this.renderItem} renderHeader={this.renderHeader}/>;
  }
}

export default compose(
  graphql(gql`
    mutation getUserContact($contact:String!) {
      getUserContact(contact:$contact)
    }
  `, {
    name: 'getUserContact',
    props: ({getUserContact}) => {
      return {
        getUserContact: (contact) => getUserContact({variables:{contact}})
      }
    }
  }),
  graphql(gql`
    mutation notifyCustomer($orderId:String!) {
      notifyCustomer(orderId:$orderId)
    }
  `, {
    name: 'notifyCustomer',
    props: ({notifyCustomer}) => {
      return {
        notifyCustomer: (orderId) => notifyCustomer({variables:{orderId}})
      }
    }
  }),
  graphql(gql`
    query OrderList($search:String,$offset:Int,$limit:Int,$date:String,$history:Boolean) {
      orders(search:$search,offset:$offset,limit:$limit,date:$date,history:$history) {
        id
        displayId
        userId
        status {
          statusId
        }
        shipping {
          title
          addressId
          contact
          postalCode
          displayDate
          date
        }
        ...OrderListItem
      }
    }
    ${OrderListItem.fragments.order}
  `, {
    options: ({search, offset=0, date, history}) => {
      return {
        variables: {
          search,
          history,
          offset,
          limit: 100,
          date,
        }
      };
    },
    props: ({ownProps, data:{orders, refetch, fetchMore, loading}}) => {
      let countMap = {};
      let pickupCount = 0, deliveryCount=0, locaton={};
      if (orders) {
        orders.map(({userId, status, shipping}) => {
          if (countMap[userId]) {
            countMap[userId]++;
          } else {
            countMap[userId] = 1;
          }

          if (shipping.title[0]&&(shipping.title[0]==='P')) {
            pickupCount++;
          } else {
            deliveryCount++;
          }
          locaton[shipping.addressId] = true;
        });
      }

      return {
        orders,
        loading,
        refetch,
        countMap,
        pickupCount,
        deliveryCount,
        locationCount: Object.keys(locaton).length,
        fetchMore: () => loadMoreData(fetchMore, orders, 'orders')
      };
    }
  })
)(OrderList);



